package cn.ztuo.bitrade.controller;

import cn.ztuo.bitrade.constant.BooleanEnum;
import cn.ztuo.bitrade.constant.MemberLevelEnum;
import cn.ztuo.bitrade.dao.TradeInfoDao;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.entity.transform.AuthMember;
import cn.ztuo.bitrade.pagination.Criteria;
import cn.ztuo.bitrade.pagination.Restrictions;
import cn.ztuo.bitrade.service.*;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import cn.ztuo.bitrade.util.Md5;
import cn.ztuo.bitrade.util.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.messaging.core.MessageRequestReplyOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;


import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.ztuo.bitrade.constant.SysConstant.SESSION_MEMBER;

@Slf4j
@RestController
@RequestMapping("/trade")
public class TradeController extends BaseController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private CoinService coinService;
    @Autowired
    private MemberWalletService memberWalletService;

    @Autowired
    private AccessRecordService accessRecordService;

    @Autowired
    private TradeInfoDao tradeInfoDao;

    @Autowired
    private SysCfService sysCfService;
    private Long id;

    @RequestMapping("info")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult info(@SessionAttribute(SESSION_MEMBER) AuthMember authMember,String trxAddress,String jyPassword, BigDecimal odfNum) throws Exception {
        if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");

        SysCf config = sysCfService.configOneCname("tradeopne");
        if (config.getValue().equals("2")) {
            return error("暂未开放！");
        }
        Member member = memberService.findOne(authMember.getId());
        if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
       // if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

        //验证交易密码
        String mbPassword = member.getPassword();
        if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置安全密码！");
        if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
            return MessageResult.error(500, "安全密码错误！");

        if(odfNum.compareTo(BigDecimal.ZERO) <=0)
            return MessageResult.error(500, "请输入正确的兑换数量！");

        Coin coin = coinService.findByUnit("ODF");
        MemberWallet memberWallet = memberWalletService.findByCoinAndMember(coin, member);

        if (memberWallet.getBalance().compareTo(odfNum) < 0) return error("余额不足！");
 
        boolean isMatch = Pattern.matches("^[A-Z][a-zA-Z0-9]*$", trxAddress);
        if(!isMatch)
            return MessageResult.error(500, "TRX地址错误！");

        if(trxAddress.length() !=34)
            return MessageResult.error(500, "TRX地址错误！");

            memberWalletService.decreaseBalance(memberWallet.getId(),odfNum);
            ///冻结钱包余额
            // memberWalletService.freezeBalance(memberWallet,odfNum);
            //增加到TradeInfo表
            TradeInfo tradeInfo = new TradeInfo();
            tradeInfo.setMemberId(member.getId());
            tradeInfo.setOdfNum(odfNum);
            tradeInfo.setStatus(1);
            tradeInfo.setTargetaddr(trxAddress);
            tradeInfo.setTradeTime(new Date());
            tradeInfoDao.save(tradeInfo);
            return  success("操作成功");
    }

    @RequestMapping("isOpen")
    public MessageResult isTradeOpen()
    {
        SysCf sysCf = sysCfService.configOneCname("tradeopne");
        String limit = sysCf.getValue();
        if(limit.equals("1"))
            return success("1");
        else
            return success("0");
    }

    @RequestMapping("setOpen")
    public MessageResult setTradeOpen(String value)
    {
        SysCf sysCf = sysCfService.configOneCname("tradeopne");
        sysCf.setValue(value);
        sysCfService.save(sysCf);
        return success("操作成功");
    }

    @RequestMapping("getCfcPrice")
    public MessageResult getTradeCfcPrice()
    {
        SysCf sysCf = sysCfService.configOneCname("tradecfcprice");
        String limit = sysCf.getValue();
        return success(limit);
    }

    @RequestMapping("setCfcPrice")
    public MessageResult setTradeCfcPrice(String value)
    {
        SysCf sysCf = sysCfService.configOneCname("tradecfcprice");
        sysCf.setValue(value);
        sysCfService.save(sysCf);
        return success("操作成功");
    }

    @RequestMapping("getpage")
    public MessageResult GetTradeInfoPage(@SessionAttribute(SESSION_MEMBER) AuthMember authMember,@RequestParam int pageNum,
                                      @RequestParam int pageSize)
    {
        MessageResult mr =new MessageResult();
        Sort orders = Criteria.sortStatic("id");
        PageRequest pageRequest = new PageRequest(pageNum-1, pageSize, orders);
        Criteria<TradeInfo> specification = new Criteria<TradeInfo>();

        specification.add(Restrictions.eq("memberId",authMember.getId(),true));

        Page<TradeInfo> page = tradeInfoDao.findAll(specification,pageRequest);
        mr.setCode(0);
        mr.setMessage("success");
        mr.setData(page);
        return mr;
    }

}
